import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfo, logout } from '@/api/login'

const user = {
  state: {
    token: '',
    name: '',
    userType: '',
    welcome: '',
    avatar: '',
    roles: [],
    portalConfigs: [],
    defaultPortal: {},
    info: {},
    platformVersion: '',
    sysNoticeList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_PORTAL_CONFIG: (state, portalConfigs) => {
      state.portalConfigs = portalConfigs
    },
    SET_DEFAULT_PORTAL: (state, defaultPortal) => {
      state.defaultPortal = defaultPortal
    },
    SET_PLATFORM_VERSION: (state, platformVersion) => {
      state.platformVersion = platformVersion
    },
    SET_NOTICE_LIST: (state, sysNoticeList) => {
      state.sysNoticeList = sysNoticeList
    }
  },

  actions: {
    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(result => {
          console.log(result)
          const { version, user, roles, permissions, sysNoticeList } = result.data
          const avatar = require('@/assets/images/profile.jpg')
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', roles)
            commit('SET_PERMISSIONS', permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.name)
          commit('SET_AVATAR', avatar)
          commit('SET_USER_TYPE', user.userType)
          commit('SET_PLATFORM_VERSION', version)
          commit('SET_NOTICE_LIST', sysNoticeList)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // // 登出
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(result => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }

  }
}

export default user
